package com.redstar.study;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.SubMenu;
import com.deaux.fan.FanView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.SQLException;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Layout;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class Practice extends SherlockActivity implements OnClickListener, OnNavigationListener{
	
	private DataBaseHelper myDbHelper;
	private List<Word> listOfWords;
	private LinearLayout card;
	private TextView question;
	private TextView answer;
	private RatingBar rating;
	private Button XButton;
	private Button OButton;
	private int currentWord = 0;
	private String[] filters;	
	private String OPTION_FILTER = "";
	private String OPTION_ORDER = "Kana DESC";
	private boolean RandomOrder = true;
	private Random randomGenerator = new Random();
	 
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;

    GoogleAnalyticsTracker tracker;

	static final int DIALOG_NO_WORDS = 3;
    
	private SharedPreferences preferences;
	private boolean JAPANESE_ANSWERS;
	private boolean SKIP_LEARNT;
	private FanView fan;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    tracker = GoogleAnalyticsTracker.getInstance();
	    getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setTitle("Practice");
	    // Start the tracker in manual dispatch mode...
	    tracker.startNewSession("UA-29340571-1",20, this);
	    setContentView(R.layout.test);
	    
		fan = (FanView) findViewById(R.id.fan_view);
		fan.setViews(R.layout.practice, R.layout.fan);

		String[] fanOptions = getResources().getStringArray(R.array.list);    
		FanMenuAdapter fanAdapter = new FanMenuAdapter(this, fanOptions);
		
		ListView fanList = (ListView) findViewById(R.id.fan_list);
		fanList.setAdapter(fanAdapter);		
		
		/*fanList.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long ID) {
				// TODO Auto-generated method stub
				
				Intent i;
				
				switch (position) {
				case 0:
					i = new Intent(Practice.this, PracticePreferences.class);
					break;
				case 1:
					i = new Intent(Practice.this, QuizPreferences.class);
					break;
				case 2:
					i = new Intent(Practice.this, Dictionary.class);
					break;
				default:
					i = new Intent();
				}
				Practice.this.startActivity(i);
				
			}
			
		});*/
		
		// set preferences
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		// get the amount of the questions to be asked from preferences
		JAPANESE_ANSWERS = preferences.getBoolean("Japanese Answers", false);
		SKIP_LEARNT = preferences.getBoolean("Skip Learnt", true);
	
		myDbHelper = new DataBaseHelper(this);
		createDB();
		listOfWords = myDbHelper.getAllVocab(SKIP_LEARNT);
		currentWord = new Random().nextInt(listOfWords.size()-1);
		
		if(listOfWords.isEmpty()){
			showDialog(DIALOG_NO_WORDS);
		}else{
			setupViews();	
		}		
		tracker.trackPageView("/Practice");
	}
	

	
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.practice);
		
		setupViews();
	}
	
	private void setupViews() {
		// TODO Auto-generated method stub
        // Gesture detection
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        };
		
        card  = (LinearLayout) findViewById(R.id.CardLayout);
		question = (TextView) findViewById(R.id.PrQuestionTV);
		rating = (RatingBar) findViewById(R.id.PrRatingBar);
		answer = (TextView) findViewById(R.id.PrAnswerTV);
		XButton = (Button) findViewById(R.id.XButton);
		OButton = (Button)  findViewById(R.id.OButton);
		

		card.setOnClickListener(Practice.this);
		card.setOnTouchListener(gestureListener);

		XButton.setOnClickListener(new OnClickListener(){

		public void onClick(View v) {
				// Update rating - 1
			Word tempWord = listOfWords.get(currentWord);
				
			if(tempWord.getRating()>0){
				double NewRating = tempWord.getRating() - 1;
				listOfWords.get(currentWord).setRating(NewRating);
				myDbHelper.setRating(tempWord, NewRating);
			}
			
			if(RandomOrder){
				currentWord = randomGenerator.nextInt(listOfWords.size()-1);
				Log.d("Order", "number = " + currentWord);
			}
			else 
			{
				if(currentWord>=listOfWords.size()-1){
					currentWord=0;
				}
				else
					currentWord++;
			}
			
			
			setWord();			
		}

		});
		OButton.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
					// Update rating + 1
					Word tempWord = listOfWords.get(currentWord);
					if(tempWord.getRating()<5){
						double NewRating = tempWord.getRating() + 1;
						listOfWords.get(currentWord).setRating(NewRating);
						myDbHelper.setRating(tempWord, NewRating);
					}
					if(RandomOrder){
						currentWord = randomGenerator.nextInt(listOfWords.size()-1);
						Log.d("Order", "number = " + currentWord);
					}
					else 
					{
						if(currentWord>=listOfWords.size()-1){
							currentWord=0;
						}
						else
							currentWord++;
					}
					
					setWord();			
				}
				
			});
		
		

		setWord();
	}

	class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					
					if(RandomOrder){
						currentWord = randomGenerator.nextInt(listOfWords.size()-1);
						Log.d("Order", "number = " + currentWord);
					}
					else{
						if(currentWord!=listOfWords.size()-1){
							//make your object/character move left 
							currentWord=currentWord+1;
						}
						else
							currentWord=0;
						}  
                	}
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					if(RandomOrder){
						currentWord = randomGenerator.nextInt(listOfWords.size()-1);
						Log.d("Order", "number = " + currentWord);
					}
					else{
						if(currentWord!=0)
						{
							currentWord=currentWord-1;
						}//make your object/character move right 
						else
							currentWord=listOfWords.size()-1;
						}
                }

				setWord();

            } catch (Exception e) {
                // nothing
            }
            return true;
        }
    }	


	protected Dialog onCreateDialog(int id) {
		Dialog dialog = new Dialog(this);//<=====THIS
	    
	    switch(id) {
    	
	    case DIALOG_NO_WORDS:
	    	dialog = new Dialog(this);
	    	dialog.setContentView(R.layout.result_dialog);
	    	dialog.setTitle("Nothing to practice!!!");
	    	TextView TV1 = (TextView) dialog.findViewById(R.id.ResultPercentTV);
	    	TV1.setText( "You have gotten 5 stars on every word");
	    	RatingBar Rating1 = (RatingBar)  dialog.findViewById(R.id.ResultRating);
	    	Rating1.setVisibility(View.INVISIBLE);
	    	Button button1 = (Button) dialog.findViewById(R.id.ResultBN);
	    	
	    	button1.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					Intent i = new Intent(Practice.this, MainScreen.class);
					Practice.this.startActivity(i);					
				}
	    		
	    	});
	    	break;
	    default:
	    	dialog = null;
	    }
	    return dialog;
	}
	
	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		// TODO Auto-generated method stub
		
		filters = getResources().getStringArray(R.array.filters);
		
        Context context = getSupportActionBar().getThemedContext();
        ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.filters, R.layout.sherlock_spinner_item);
        list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
 
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        getSupportActionBar().setListNavigationCallbacks(list, this);
	
        return super.onCreateOptionsMenu(menu);
	}


	
	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.practice_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.groupItemAll:
			OPTION_FILTER = "";
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;
		case R.id.groupItemAdj:
			OPTION_FILTER = "adj";
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;
		case R.id.groupItemNoun:
			OPTION_FILTER = "n";
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;
		case R.id.groupItemRU:
			OPTION_FILTER = "ru-v";
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;
		case R.id.groupItemU:
			OPTION_FILTER = "u-v";
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;
		case R.id.groupItemOrderAll:
			OPTION_ORDER = "Kana DESC";
			RandomOrder = false;
			Log.d("Menu","All set - ");
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;
		case R.id.groupItemRating:
			OPTION_ORDER = "Rating";
			RandomOrder = false;
			Log.d("Menu","rating set - ");
			setOptions(OPTION_FILTER, OPTION_ORDER);
			item.setChecked(true);
			break;	
		case R.id.groupItemRandom:
			RandomOrder = true;
			Log.d("Menu","random set - "+ RandomOrder);
			item.setChecked(true);
			break;		

			
		default:
			return super.onOptionsItemSelected(item);
		}
		return false;
	}*/

	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
	    switch (item.getItemId()) {
        case android.R.id.home:
            // display menu
        	displayMenu();

            return true;
        default:
            return super.onOptionsItemSelected(item);
	    }
	}

	private void displayMenu() {
		// TODO Auto-generated method stub
		fan.showMenu();		
	}

    public void unclick(View v) {
    	System.out.println("CLOSE");
    	fan.showMenu();
    }
    
    public void click(View v) {
    	System.out.println("OPEN");
    	fan.showMenu();
    }
	/* when you set the filter you need to 
	 * 1. get new words
	 * 2. reset the progress bar
	 * 3. set new progress bar size.
	 * 4. reset current word */



	private void setOptions(String filter, String order) {
		// TODO Auto-generated method stub
		listOfWords = myDbHelper.getVocabWithOptions(filter, order, SKIP_LEARNT);	
		currentWord = randomGenerator.nextInt(listOfWords.size()-1);
		setWord();
	}




	private void setWord() {
		// TODO Auto-generated method stub
		Word tempWord = listOfWords.get(currentWord);
		if(JAPANESE_ANSWERS){
			question.setText(tempWord.getDefinition() + " \n " + tempWord.getType());
			setJapaneseTextView(answer, currentWord);
		}else{
			setJapaneseTextView(question, currentWord);
			answer.setText(tempWord.getDefinition() + " \n " + tempWord.getType());
		}
		
		answer.setTextColor(0xFFFFFFFF);
		XButton.setVisibility(View.INVISIBLE);
		OButton.setVisibility(View.INVISIBLE);
		rating.setRating((float) tempWord.getRating());
	}

	private void setJapaneseTextView(TextView ans,
			int currentWord) {
		// TODO Auto-generated method stub
		String kanji = listOfWords.get(currentWord).getKanji();
		String kana =  listOfWords.get(currentWord).getKana();
		
		if(kanji==null){
			ans.setText(kana);
		}
		else{
			ans.setText(kanji + "\n" + kana);
		}		
	}

	private void createDB() {
		// TODO Auto-generated method stub
		try {
			myDbHelper.createDataBase();
		}
		catch (IOException ioe) {
			throw new Error("Unable to create database");
		}
		try {
			myDbHelper.openDataBase();
		}
		catch(SQLException sqle){
			throw sqle;
		}
	}

	public void onClick(View v) {
		
		if(XButton.getVisibility()==View.VISIBLE){
			answer.setTextColor(0x00000000);
			XButton.setVisibility(View.INVISIBLE);
			OButton.setVisibility(View.INVISIBLE);			
		}else{
			answer.setTextColor(0xFF000000);
			XButton.setVisibility(View.VISIBLE);
			OButton.setVisibility(View.VISIBLE);			
		}

		
	}
	
	@Override
    public void onDestroy() {
        super.onDestroy();
        myDbHelper.close();
        // Stop the tracker when it is no longer needed.
        tracker.stopSession();

	}



	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		if(filters[itemPosition].equals("All")){
			OPTION_FILTER = "";
			setOptions(OPTION_FILTER, OPTION_ORDER);
		}
		else if(filters[itemPosition].equals("Adjectives")){
			OPTION_FILTER = "adj";
			setOptions(OPTION_FILTER, OPTION_ORDER);			
		}
		else if(filters[itemPosition].equals("Noun")){
			OPTION_FILTER = "n";
			setOptions(OPTION_FILTER, OPTION_ORDER);
		}
		else if(filters[itemPosition].equals("Verbs")){
			OPTION_FILTER = "u-v";
			setOptions(OPTION_FILTER, OPTION_ORDER);
		}

		// TODO Auto-generated method stub
		return false;
	}




}
